﻿using System;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using System.Xml.Linq;
namespace nicotool
{
   /// <summary>
   /// 动画路径信息
   /// </summary>
  public  class FlvInfo
    {
        /// <summary>
        /// 動画ID
        /// </summary>
        public string Id { get; set; }
        /// <summary>
        /// ThreadI 
        /// </summary>
        public string ThreadId { get; set; }
        /// <summary>
        /// FLV网址
        /// </summary>
        public string FlvUrl { get; set; }
        /// <summary>
        /// 错误信息URL
        /// </summary>
        public string AbuseLink { get; set; }
        /// <summary>
        /// 信息服务URL
        /// </summary>
        public string MessageServer { get; set; }
      /// <summary>
      /// 动画路径信息
      /// </summary>
      private FlvInfo()
        {
            
        }

      
      /// <summary>
      ///指定动画信息获得
      /// </summary>
      /// <param name="id"></param>
      /// <returns></returns>
      public static FlvInfo Create(string id)
      {
          //获得HttpWebRequest
          HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(StrUrl.getInfo(id));
          if (nico_data.proxy != null)
          {

              req.Proxy = nico_data.proxy;
          }
          req.CookieContainer = nicovideo.LoginCookie; //设置cookie

          StreamReader sr; //定义读取流
          try
          {
              WebResponse resp = req.GetResponse(); //获取response响应
              sr = new StreamReader(resp.GetResponseStream()); //读取响应流
          }
          catch (Exception ex)
          {

              throw new Exception(ex.Message);
          }
          string str = sr.ReadToEnd(); //读取流信息
          //systool.fileWrite(str, AppDomain.CurrentDomain.BaseDirectory + "yuans.txt");
          
          
          //分割字符串；//二次分割字符串变成成组
       //   var dict = str.Split('&').Select(t => t.Split('=')).ToDictionary(splitted => splitted[0], splitted => HttpUtility.UrlDecode(splitted[1]));

          string[] dict = str
                  .Split('&');

          //StringBuilder sb = new StringBuilder();
          //foreach (string item in dict)
          //{
          //    sb.Append(item + "\r\n");

          //}
       //   systool.fileWrite(sb.ToString(), AppDomain.CurrentDomain.BaseDirectory + "gesh.txt");

          var zd = dict.Select(t => t.Split('=')).ToDictionary(splitted => splitted[0], splitted => HttpUtility.UrlDecode(splitted[1]));
       
         
        
          //        .Select(t => t.Split('='))
          //        .ToDictionary(splitted => splitted[0], splitted => HttpUtility.UrlDecode(splitted[1]));
          
          //判断返回信息是否正确
          if ((zd.ContainsKey("closed") && zd["closed"] == "1") || !zd.ContainsKey("url"))
          {
              throw new Exception("获取视频信息错误.");
          }

          
          try
          {
              FlvInfo info = new FlvInfo();
              info.Id = id;
              info.FlvUrl = zd["url"];
              info.AbuseLink = zd["link"];
              info.ThreadId = zd["thread_id"];
              info.MessageServer = zd["ms"];
              return info;
          }
          catch (Exception ex)
          {
              throw new Exception(ex.Message);
          }
         
      }

      /// <summary>
      /// 获得指定数量的动画的评论
      /// </summary>
      /// <param name="num">数量</param>
      /// <returns></returns>
      public string[] GetComments(int num)
      {
          var req = (HttpWebRequest)HttpWebRequest.Create(MessageServer);//信息网址
          if (nico_data.proxy != null)
          {

              req.Proxy = nico_data.proxy;
          }
          req.Method = "POST";//设置请求为post
          var s =StrUrl.getComment(num,ThreadId);//弹幕信息
          var bs = Encoding.UTF8.GetBytes(s); //编码
          req.ContentLength = bs.Length;    //编码长度
          req.CookieContainer = nicovideo.LoginCookie; //设置cookie
          req.GetRequestStream().Write(bs, 0, bs.Length); //写入流

          XDocument doc; //定义xml
          try
          {
              var resp = (HttpWebResponse)req.GetResponse(); //获得响应信息

              doc = XDocument.Load(resp.GetResponseStream()); //转为xml
      //        doc.Save(AppDomain.CurrentDomain.BaseDirectory + Id+ "弹幕.xml"); //导出为xml
          }
          catch (Exception ex)
          {
              
              throw new Exception("获得xml出错",ex);
          }
          try
          {
              return doc.Descendants("chat").Select(x => x.Value).ToArray();
          }
          catch (Exception ex)
          {

              throw new Exception("获得xml信息错误", ex);
          }

           
      }



      /// <summary>
      /// 获得指定数量的动画的评论
      /// </summary>
      /// <param name="num">数量</param>
      /// <returns></returns>
      public XDocument GetComments_xml(int num)
      {
          var req = (HttpWebRequest)HttpWebRequest.Create(MessageServer);//信息网址
          if (nico_data.proxy != null)
          {

              req.Proxy = nico_data.proxy;
          }
          req.Method = "POST";//设置请求为post
          var s = StrUrl.getComment(num, ThreadId);//弹幕信息
          var bs = Encoding.UTF8.GetBytes(s); //编码
          req.ContentLength = bs.Length;    //编码长度
          req.CookieContainer = nicovideo.LoginCookie; //设置cookie
          req.GetRequestStream().Write(bs, 0, bs.Length); //写入流

          XDocument doc; //定义xml
          try
          {
              var resp = (HttpWebResponse)req.GetResponse(); //获得响应信息

              doc = XDocument.Load(resp.GetResponseStream()); //转为xml
           //   doc.Save(AppDomain.CurrentDomain.BaseDirectory + Id + "弹幕.xml"); //导出为xml
          }
          catch (Exception ex)
          {

              throw new Exception("获得xml出错", ex);
          }
          try
          {
              return doc;
          }
          catch (Exception ex)
          {

              throw new Exception("获得xml信息错误", ex);
          }


      }
    }
}
